import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Like } from 'typeorm';
import { Application } from './entities/application.entity';
import { AddApplicationDto } from './dto/add-application.dto';

@Injectable()
export class ApplicationService {
  constructor(@InjectRepository(Application) private applicationRepository: Repository<Application>) {}

  // 添加应用
  async addApplication(addApplicationDto: AddApplicationDto) {
    return await this.applicationRepository.save(addApplicationDto);
  }
  // 查询收藏的应用
  async findCollectApplications(user_id: number) {
    return await this.applicationRepository.find({
      where: {
        user_id,
        is_collect: '1',
      },
    });
  }
  // 查询应用
  async findQueryApplications(user_id: number, keyword?: string, aid?: number) {
    return await this.applicationRepository.find({
      where: {
        user_id,
        aid: aid ? aid : undefined,
        name: keyword ? Like(`%${keyword}%`) : undefined, // 在 TypeORM 中，undefined 的查询条件会被自动忽略
      },
    });
  }
  // 修改应用名称、图标和背景色
  async updateApplicationName(aid: number, name?: string, icon?: string, bgColor?: string[], bgColorType?: string) {
    const updateData: { name?: string; icon?: string; bg_color?: string[]; bg_color_type?: string } = {};
    if (name !== undefined) {
      updateData.name = name;
    }
    if (icon !== undefined) {
      updateData.icon = icon;
    }

    if (bgColor !== undefined) {
      updateData.bg_color = bgColor;
    }
    if (bgColorType !== undefined) {
      updateData.bg_color_type = bgColorType;
    }
    return await this.applicationRepository.update(aid, updateData);
  }
  // 删除应用
  async deleteApplication(aid: number) {
    return await this.applicationRepository.delete(aid);
  }
  // 收藏应用
  async collectApplication(aid: number) {
    return await this.applicationRepository.update(aid, { is_collect: '1' });
  }
  // 取消收藏应用
  async cancelCollectApplication(aid: number) {
    return await this.applicationRepository.update(aid, { is_collect: '0' });
  }
  // 批量收藏应用
  async batchCollectApplications(aids: number[]) {
    if (aids && aids.length === 0) {
      return { affected: 0, raw: [], generatedMaps: [] };
    }
    return await this.applicationRepository.update(aids, { is_collect: '1' });
  }
  // 批量取消收藏应用
  async batchCancelCollectApplications(aids: number[]) {
    if (aids && aids.length === 0) {
      return { affected: 0, raw: [], generatedMaps: [] };
    }
    return await this.applicationRepository.update(aids, { is_collect: '0' });
  }
  // 增加应用点击次数
  async incrementClickCount(aid: number) {
    // 首先获取当前应用
    const application = await this.applicationRepository.findOne({
      where: { aid },
    });
    if (!application) {
      throw new NotFoundException('应用不存在');
    }

    // 增加点击次数
    const newClickCount = (application.click_count || 0) + 1;
    // 更新点击次数
    return await this.applicationRepository.update(aid, { click_count: newClickCount });
  }
  // 查询最近使用的应用
  async findRecentApplications(user_id: number) {
    return await this.applicationRepository.find({
      where: {
        user_id,
      },
      order: {
        click_count: 'DESC',
      },
      take: 2,
    });
  }
  // 更新应用图片
  async updateApplicationImage(aid: number, image_url: string) {
    const application = await this.applicationRepository.findOne({
      where: { aid },
    });
    if (!application) {
      throw new NotFoundException('应用不存在');
    }
    return await this.applicationRepository.update(aid, { image_url });
  }
}
